package com.sikaryofficial.backend.message.consumer;

import com.sikaryofficial.backend.annotation.TenantFilter;
import com.sikaryofficial.backend.domain.entity.ActivityResult;
import com.sikaryofficial.backend.message.body.ActivityResultUserInfoMessage;
import com.sikaryofficial.backend.service.IActivityResultService;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.system.api.RemoteUserService;
import com.sikaryofficial.system.api.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 获奖结果-用户信息处理
 */
@Component
@Slf4j
public class ActivityResultProcess {
    @Autowired
    private IActivityResultService activityResultService;
    @Resource
    private RemoteUserService remoteUserService;
    /**
     * 消息监听
     * <p>
     * 获奖结果信息补充业务-消费流程
     *
     * @param message 消息
     */
    @StreamListener(MQConsumer.BINDINGS_ACTIVITY_RESULT_USERINFO_INPUT)
    @TenantFilter
    public void onActivityResultUserInfoMessage(@Payload ActivityResultUserInfoMessage message) {
        log.info("=========================################==================================");
        log.info("[onMessage][线程编号:{} 消息内容：{}]", Thread.currentThread().getId(), message);
        log.info("==========================###################===============================");
        /**
         *  获奖后，需发送MQ消息，补充用户相关信息
         * 目前计划采用MQ异步消息处理
         */
        Long activityResultId = message.getActivityResultId();
        ActivityResult activityResult = activityResultService.getById(activityResultId);
        if (Objects.isNull(activityResult) || Objects.isNull(activityResult.getCreatedBy())) {
            log.error("ActivityResultUserInfo : userId is empty.");
            return;
        }
        // 获取用户信息
        Long userId = activityResult.getCreatedBy();
        R<SysUser> data = remoteUserService.getUserByUserId(userId);
        if (Objects.isNull(data) || Objects.isNull(data.getData())) {
            log.error("ActivityResultUserInfo : user data is empty.");
            return;
        }
        SysUser user = data.getData();
        // 补充如下信息，进行结果数据更新
        activityResult.setNickName(user.getNickName());
        activityResult.setEmail(user.getEmail());
        activityResultService.updateById(activityResult);
    }
}
